﻿using System;
using System.ComponentModel;

namespace Util
{
    public static class EnumExtensions
    {
        /// <summary>
        /// Gets the attribute of a specific type of the given enum member.
        /// </summary>
        /// <param name="value">An enum member.</param>
        /// <returns>
        /// The first attribute of type T, or null if not found.
        /// </returns>
        public static T GetAttribute<T>(this Enum value) where T : Attribute
        {
            var type = value.GetType();
            var memberInfo = type.GetMember(value.ToString());
            if (memberInfo != null && memberInfo.Length > 0)
            {
                var attributes = memberInfo[0].GetCustomAttributes(
                    typeof(T), false);
                if (attributes != null && attributes.Length > 0)
                    return (T)attributes[0];
            }
            return null;
        }

        /// <summary>
        /// Gets the description of the given enum member. This description
        /// is retrieved from the DescriptionAttribute associated with this
        /// enum member. If no DescriptionAttribute is associated with this
        /// enum member, returns null.
        /// </summary>
        /// <param name="value">An enum member.</param>
        /// <returns>Its description, or null if not found.</returns>
        public static string GetDescription(this Enum value)
        {
            var attribute = GetAttribute<DescriptionAttribute>(value);
            if (attribute != null)
                return attribute.Description;
            else
                return null;
        }
    }
}
